package com.lh.java.nio;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class MyServer {
	SocketChannel sc;

	ServerSocketChannel ssc;

	Selector selector;

	private static Charset charset = Charset.forName("US-ASCII");

	private static CharsetEncoder encoder = charset.newEncoder();

	private static CharsetDecoder decoder = charset.newDecoder();

	ByteBuffer br = ByteBuffer.allocate(1024);

	MyServer() {
		try {
			InetSocketAddress addr = new InetSocketAddress(
					InetAddress.getLocalHost(), 26);

			ssc = ServerSocketChannel.open();
			ssc.configureBlocking(false);
			ServerSocket ss = ssc.socket();
			ss.bind(addr);
			System.out.println("asdf");
			selector = Selector.open();
			ssc.register(selector, SelectionKey.OP_ACCEPT);

			while (true) {
				if (selector.select() > 0) {
					System.out.println("asdf");
					Set readyKeys = selector.selectedKeys();
					Iterator it = readyKeys.iterator();
					while (it.hasNext()) {
						SelectionKey sk = (SelectionKey) it.next();
						it.remove();
						if (sk.isAcceptable()) {
							sc = ssc.accept();
							sc.read(br);
							br.flip();
							CharBuffer cb = decoder.decode(br);
							System.out.print(" : " + cb);
							sc.configureBlocking(false);
							sk = sc.register(selector, 0);
							sk.interestOps(SelectionKey.OP_WRITE);
							System.out.println("isaccept()");
							// selector.wakeup();
						}
						if (sk.isReadable()) {
							sc.read(br);
							br.flip();
							CharBuffer cb = decoder.decode(br);
							System.out.print("is readable  : " + cb);
							sk.interestOps(SelectionKey.OP_WRITE);
							System.out.println("set write");
							// selector.wakeup();
						}
						if (sk.isWritable()) {
							String now = new Date().toString();
							sc.write(encoder.encode(CharBuffer.wrap("write"
									+ now + "/r/n")));
							System.out.println(sc.socket().getInetAddress()
									+ " : " + now);
							sk.interestOps(SelectionKey.OP_READ);
							// selector.wakeup();

						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				sc.close();
				ssc.close();

			} catch (Exception e) {
			}
		}

	}

	public static void main(String args[]) {
		new MyServer();
	}
}
